<template>
  <el-select
    v-model="selectValue"
    :multiple="$attrs.multiple"
    :key="isMultiple"
    style="width: 100%"
    collapse-tags
    :filterMethod="filterMethod"
    @change="changeSelectValue"
    @visible-change="visibleChange"
  >
    <el-option
      v-for="(item, index) in options"
      :key="item.value || index"
      :label="
        getLen(item.key) > 20 ? item.key.substring(0, 20) + '...' : item.key
      "
      :value="item.value"
    />
  </el-select>
</template>

<script setup name="slipSelect">
import pinyin from 'js-pinyin'
import { onMounted } from 'vue'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  modelValue: {
    type: [Number, String, Array],
  },
  api: {
    type: Function,
  },
  query: {
    type: Object,
  },
  keyField: {
    type: String,
    default: 'name',
  },
  valueField: {
    type: String,
    default: 'id',
  },
  defaultValue: {
    type: Boolean,
    default: false,
  },
  clearType: {
    type: Boolean,
    default: true,
  },
  slipSelectRequest: {
    type: Boolean,
    default: false,
  },
  isMultiple: {
    type: String,
  },
})

const selectValue = ref(proxy.$attrs.multiple ? [] : '')
const options = ref([])
const copyOptions = ref([])
// 单选多选数据类型为字符串和数组
function setSelectValue() {
  return proxy.$attrs.multiple ? [] : ''
}
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      if (proxy.$attrs.multiple) {
        //转整型
        selectValue.value = proxy.$fn.splitArr(val).map((item) => {
          return item.toString()
        })
      } else {
        selectValue.value = val
      }
    } else {
      selectValue.value = setSelectValue()
    }
    // init()
  }
)
watch(
  () => props.clearType,
  (val) => {
    selectValue.value = setSelectValue()
  }
)
watch(
  () => props.slipSelectRequest,
  (val) => {
    // 这些代码会导致偏好设置设置默认值报错，而且涉及全局，逻辑看起来有明显错误，暂时注释
    // if (val) {
    //   if (proxy.$attrs.multiple) {
    //     //转整型
    //     let splitVal = proxy.$fn.splitArr(val).map((item) => item.toString())
    //     console.log(splitVal)
    //     if (splitVal.length && splitVal[0] != 'true') {
    //       selectValue.value = splitVal
    //     }
    //   } else {
    //     selectValue.value = val
    //   }
    // } else {
    //
    //   selectValue.value = setSelectValue()
    // }
    init()
  }
)
watch(
  () => selectValue.value,
  (val) => {
    if (Array.isArray(val)) {
      emits('update:modelValue', val.toString())
    }
  }
)

onMounted(() => {
  proxy.$nextTick(() => {
    init()
  })
})

function visibleChange(val) {
  //下拉框出现/隐藏时触发
  if (!val) {
    options.value = copyOptions.value
  }
}
function filterMethod(value) {
  // 自定义搜索方法
  if (value) {
    let result = []
    copyOptions.value.forEach((item) => {
      pinyin.setOptions({ checkPolyphone: false, charCase: 1 })
      const resultEng = pinyin.getCamelChars(item.key).toUpperCase()
      const matchResult =
        item.key.indexOf(value) !== -1 ||
        resultEng.indexOf(value.toUpperCase()) !== -1
      // let matchResult = PinYinMatch.match(item.key, value)
      if (matchResult) {
        result.push(item)
      }
    })
    options.value = result
  } else {
    options.value = copyOptions.value
  }
}

function getLen(str = '') {
  if (str) {
    return Array.from(str).length
  } else {
    return 0
  }
}
function changeSelectValue(val) {
  if (proxy.$attrs.multiple) {
    emits('update:modelValue', val.toString())
  } else {
    emits('update:modelValue', val)
  }
  emits('changeValue', val)
}
function init() {
  const api = props.api
  if (api) {
    api(props.query).then((resp) => {
      if (resp && resp.success) {
        options.value = resp.data.map((item) => {
          return {
            key: item[props.keyField],
            value: item[props.valueField].toString(),
          }
        })
        copyOptions.value = proxy.$fn.deepClone(options.value)
        let _modelValue =
          typeof props.modelValue === 'number'
            ? props.modelValue.toString()
            : props.modelValue
        if (_modelValue) {
          if (proxy.$attrs.multiple) {
            if (_modelValue.length) {
              selectValue.value = proxy.$fn
                .splitArr(_modelValue)
                .map((item) => item.toString())
            }
          } else {
            selectValue.value = _modelValue
          }
        } else {
          selectValue.value = _modelValue
        }
        if (props.defaultValue && resp.data.length) {
          selectValue.value = options.value[0].value
          emits('update:modelValue', options.value[0].value)
          emits('changeValue')
        }
      }
    })
  }
}
</script>

<style scoped></style>
